package com.carl.guli.service;

import com.carl.guli.common.util.FileUploadUtil;
import com.carl.guli.mapper.NewsMapper;
import com.carl.guli.model.News;
import com.carl.guli.model.NewsExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.util.List;

/**
 * Created by youzm on 2017/5/16.
 */
@Service
public class NewsServiceImpl implements NewsService{

    @Value("${ftp.directory}")
    private String ftpPath;

    @Value("${ftp.pic}")
    private String ftpPic;

    @Value("${ftp.download}")
    private String ftpDownload;

    @Autowired
    private NewsMapper newsMapper;

    @Override
    public List<News> listNews() {
        NewsExample example = new NewsExample();
        example.setOrderByClause("publish_time desc, create_time desc");
        List<News> newses = newsMapper.selectByExample(example);
        return newses;
    }

    @Override
    public void addNews(News news, CommonsMultipartFile[] news_pic) throws Exception {
        if (!news_pic[0].isEmpty()){
            String introPicUrl = FileUploadUtil.uploadImg(ftpPath + ftpPic, news_pic[0]);
            news.setPic(ftpDownload + ftpPic + "/" + introPicUrl);
        }

        if (news.getNewsId() == null){
            newsMapper.insertSelective(news);
        }

        if (news.getNewsId() != null){
            newsMapper.updateByPrimaryKeySelective(news);
        }
    }

    @Override
    public News findNewsById(Integer newsId) {
        return newsMapper.selectByPrimaryKey(newsId);
    }

    @Override
    public void editNews(News news) {
        newsMapper.updateByPrimaryKeySelective(news);
    }

    @Override
    public void delNews(Integer id) {
        newsMapper.deleteByPrimaryKey(id);
    }
}
